package com.dycong.common.IO.nio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by dycong on 2017/3/10.
 */
public class ClientSocketChannelTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        SocketChannel socketChannel = SocketChannel.open(); // 创建SocketChannel
        InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 28080);
        socketChannel.socket().connect(address);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        ByteBuffer buffer = ByteBuffer.allocate(1024); // 创建Buffer
        while (true) {
            try {
                buffer.clear();
                String time = sdf.format(new Date());
                buffer.put(time.getBytes());
                buffer.flip(); // 设置成读取状态
                socketChannel.write(buffer); // 发送数据
                Thread.sleep(1000);
                //TODO SocketChannel在发送数据时也可以读服务端回复数据，此处没有将通道设为非阻塞的，
                // TODO 不需要多于操作，如果设定为非阻塞的，就需要线程等待或者循环延时读取返回的数据
                //TODO 双向通道
                ByteBuffer tmp=ByteBuffer.allocate(1024);
                socketChannel.read(tmp);
                tmp.flip();
                System.out.println(ServerSelectSockets.stringFromByteBuffer(tmp));
            } catch (Exception e) {
                System.out.println("Connection Close");
                break;
            }
        }
    }

}
